import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {BaseTreeService} from '@sb/base/core/service/base-tree.service';
import {BaseNzTreeNodeOptions, BaseTreeComponent} from '@sb/base';
import {SysParamTreeNode} from '../entity/sys-param-tree-node';
import {SysParamService} from '../service/sys-param.service';
import {SysCodeSearchConfig} from '../../sys-code/entity/sys-code-tree-node';
import {NzTreeNode} from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import {Observable} from 'rxjs';
import {SysParamType} from '../entity/sys-param';

@Component({
    selector: 'sys-param-tree-select-panel',
    template: `
        <base-tree
            #baseTree
            [showSearch]="false"
            [searchConfig]="searchConfig"
            [maxLevel]="searchConfig.maxLevel"
            [globalName]="'系统参数'"
            (selectNode)="onSelectNode($event)"
            [showTypeIcon]="true"
            [typeIcon]="typeIcon"
            [checkable]="checkable"
            [showRoot]="true"
            [draggable]="draggable"
            [beforeDrop]="beforeDrop.bind(this)"
        ></base-tree>
    `,
    providers: [{
        provide: BaseTreeService,
        useClass: SysParamService
    }]
})
export class SysParamTreeSelectPanelComponent implements OnInit {

    @ViewChild('baseTree', {static: false})
    baseTree: BaseTreeComponent;


    typeIcon = {
        root: 'dr:hy-root',
        DIR: 'dr:hy-module',
        TEXT: 'file',
        NUMBER: 'file',
        SYS_CODE: 'file',
        ATTACHMENT: 'file'
    };

    @Output()
    selectNode = new EventEmitter<NzTreeNode>();

    @Input()
    searchConfig: SysCodeSearchConfig = {
        maxLevel: 1
    };

    @Input()
    draggable = false;

    @Input()
    checkable: boolean;

    constructor() {
    }

    ngOnInit(): void {
    }

    onSelectNode(nzTreeNode: NzTreeNode): void {
        this.selectNode.emit(nzTreeNode);
    }

    beforeDrop(dragNode: NzTreeNode, targetNode: NzTreeNode, pos: number): boolean | Observable<boolean> {
        if (!this.draggable) {
            return false;
        }
        const targetNodeType: SysParamType = targetNode.origin.type;
        return targetNodeType === 'DIR' || targetNodeType === 'root';
    }

    reload() {
        this.baseTree.reload();
    }

    reloadNode(nodeId) {
        this.baseTree.reloadNode(nodeId);
    }
}
